package cn.dzhang.rcp.hyperbola.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import cn.dzhang.rcp.hyperbola.Activator;
import cn.dzhang.rcp.hyperbola.common.UIConstants;
import cn.dzhang.rcp.hyperbola.dialogs.AddContactDialog;
import cn.dzhang.rcp.hyperbola.model.ContactEntry;
import cn.dzhang.rcp.hyperbola.model.ContactGroup;

public class AddContactAction extends Action implements ISelectionListener,
		IWorkbenchAction {
	private final IWorkbenchWindow window;
	public static final String ID = "cn.dzhang.rcp.hyperbola.actions.AddContactAction";
	private IStructuredSelection selection;

	public AddContactAction(IWorkbenchWindow window) {
		this.window = window;
		this.window.getSelectionService().addSelectionListener(this);

		setId(ID);
		setActionDefinitionId(ID);
		setText("&Add Contact");
		setToolTipText("Add a contact to your contact list.");
		setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
				Activator.PLUGIN_ID, UIConstants.ImagePaths.ADD_CONTACT));
	}

	@Override
	public void dispose() {
		this.window.getSelectionService().removeSelectionListener(this);
	}

	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection _selection) {
		if (_selection instanceof IStructuredSelection) {
			selection = (IStructuredSelection) _selection;
			setEnabled(selection.size() == 1
					&& selection.getFirstElement() instanceof ContactGroup);

		} else {
			setEnabled(false);
		}
	}

	@Override
	public void run() {
		Shell shell = this.window.getShell();
		AddContactDialog dialog = new AddContactDialog(shell);

		int result = dialog.open();
		switch (result) {
		case Window.OK:
			ContactGroup group = (ContactGroup) selection.getFirstElement();
			ContactEntry entry = dialog.getEntry();
			entry.setGroup(group);
			group.addEntry(entry);
			break;
		default:
			break;
		}

	}
}
